/*
 * @Author: NJ_1098 xiabaoxin
 * @Date: 2025-02-11 13:42:49
 * @LastEditors: NJ_1098 xiabaoxin
 * @LastEditTime: 2025-02-19 17:04:29
 * @Description: 用户控制器层
 */
const jwt = require("jsonwebtoken");
const {
  JWT_KEY,
  WECHAT_MP_APPID,
  WECHAT_MP_APPSECRET,
} = require("../config/config.default");
const UserService = require("../service/user.service");
const CommonUtils = require("../utils/common");
const axios = require("axios");
const {
  getOpenidError,
  systemError,
  updateError,
} = require("../constant/index.js");

class UserController {
  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 注册
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async register(ctx, next) {
    try {
      const { account, password } = ctx.request.body;
      const tempPwd = CommonUtils.encrypt(password);
      let res = await UserService.add({ account, password: tempPwd });
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: res,
      };
    } catch (err) {
      console.log(err);
      systemError.data = err.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 新增用户
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async wxAdd(ctx, next) {
    try {
      const { openid, wname, avatar } = ctx.request.body;
      let res = await UserService.add({ openid, wname, avatar });
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: res,
      };
    } catch (err) {
      console.log(err);
      systemError.data = err.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 微信登录
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async wxLogin(ctx, next) {
    try {
      const { openid } = ctx.request.body;
      let res = await UserService.getUserInfo({ openid });
      let jwtMain = {
        uid: res.uid,
        openid: res.openid,
      };
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: {
          userInfo: res,
          Authorization: jwt.sign(jwtMain, JWT_KEY, { expiresIn: "1d" }),
        },
      };
    } catch (err) {
      console.log(err);
      systemError.data = err.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 获取微信小程序openid
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async getOpenid(ctx, next) {
    try {
      const { code } = ctx.request.query;
      const res = await axios.get(
        "https://api.weixin.qq.com/sns/jscode2session",
        {
          params: {
            appid: WECHAT_MP_APPID,
            secret: WECHAT_MP_APPSECRET,
            js_code: code,
            grant_type: "authorization_code",
          },
        }
      );
      if (res.data.errcode) {
        getOpenidError.code = res.data.errcode;
        getOpenidError.msg = res.data.errmsg;
        throw new Error(res.data.errmsg);
      }
      ctx.body = {
        code: "000000",
        data: res.data,
        msg: "请求成功",
      };
    } catch (err) {
      console.log(err);
      if (getOpenidError.code) {
        ctx.app.emit("error", getOpenidError, ctx);
      } else {
        ctx.app.emit("error", systemError, ctx);
      }
      return;
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 删除用户
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async delete(ctx, next) {
    try {
      const { uids } = ctx.request.body;
      let lastOpt = uids;
      if (typeof uids === "string") {
        lastOpt = [uids];
      }
      let res = await UserService.delete(lastOpt);
      ctx.body = {
        code: "00000",
        msg: res,
        data: null,
      };
    } catch (err) {
      console.log(err);
      systemError.data = err.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 获取用户信息
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async getInfo(ctx, next) {
    try {
      const { uid } = ctx.state.userInfo;
      let res = await UserService.getUserInfo({ uid }, [
        "uid",
        "account",
        "openid",
        "name",
        "wname",
        "avatar",
        "role",
      ]);
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: res,
      };
    } catch (err) {
      console.log(err);
      systemError.data = err.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 更新用户信息
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async update(ctx, next) {
    try {
      const { password, name, avatar, role, status, reason } = ctx.request.body;
      const tempPwd = CommonUtils.encrypt(password);
      const { uid } = ctx.state.userInfo;
      let res = await UserService.update(uid, {
        password: tempPwd,
        name,
        avatar,
        role,
        status,
        reason,
      });
      if (res > 0) {
        ctx.body = {
          code: "00000",
          msg: "更新成功",
          data: null,
        };
      } else {
        ctx.app.emit("error", updateError, ctx);
      }
    } catch (err) {
      console.log(err);
      systemError.data = err.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }
}

module.exports = UserController;
